package com.gengzp.system.controller;

import com.gengzp.common.document.annotations.Api;
import com.gengzp.common.document.annotations.ApiOperation;
import com.gengzp.common.exception.BusinessException;
import com.gengzp.common.model.base.resp.Result;
import com.gengzp.common.model.user.req.AddSysUserReq;
import com.gengzp.common.model.user.req.EditUserPasswordReq;
import com.gengzp.common.model.user.req.LoginUserReq;
import com.gengzp.common.model.user.resp.LoginUserResp;
import com.gengzp.permission.annotation.AuthIgnore;
import com.gengzp.permission.utils.PermissionUtils;
import com.gengzp.system.service.ISysUserAuthenticationService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * @ClassName UserAuthenticationController
 * @Description 系统用户认证模块控制层
 * @Author gengzp
 * @Date 2025/5/10 23:14
 */
@RestController
@RequestMapping("/user/authentication")
@Api(tags = "系统用户认证模块")
public class SysUserAuthenticationController {

    @Autowired
    private ISysUserAuthenticationService userAuthenticationService;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    @ApiOperation(value = "用户注册")
    public Result<LoginUserResp> register(@Valid @RequestBody AddSysUserReq req) {
        return Result.getSuccessResult(userAuthenticationService.doRegister(req));
    }

    /**
     * 用户登录
     */
    @AuthIgnore
    @PostMapping("/login")
    @ApiOperation(value = "用户登录")
    public Result<LoginUserResp> login(@Valid @RequestBody LoginUserReq req) {
        return Result.getSuccessResult(userAuthenticationService.doLogin(req));
    }

    /**
     * 用户退出登录
     */
    @PostMapping("/quit")
    @ApiOperation(value = "用户退出登录")
    public Result<String> quit(HttpServletRequest httpServletRequest) {
        userAuthenticationService.doQuit(
                httpServletRequest.getHeader("Authorization").substring(7));
        return Result.getSuccessResult();
    }

    /**
     * 用户修改密码
     */
    @PostMapping("/edit_password")
    @ApiOperation(value = "用户修改密码")
    public Result<Void> editPassword(@Valid @RequestBody EditUserPasswordReq req) {
        // 用户只能修改自己的密码
        if (!Objects.equals(String.valueOf(PermissionUtils.getCurrentUserId()), req.getId())) {
            throw BusinessException.get("当前用户无权限修改其他用户的密码");
        }
        // 超级管理员密码无法修改
        if (Objects.equals(PermissionUtils.getSuperAdminUserId(), req.getId())) {
            throw BusinessException.get("超级管理员密码只能前往配置文件进行修改");
        }

        userAuthenticationService.doEditPassword(req);
        return Result.getSuccessResult();
    }

}
